package com.ccl.iot.views;


import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.ImageView;

import com.ccl.iot.R;
import com.ccl.iot.asynctask.SendIrTask;
import com.ccl.iot.asynctask.StudyIrTask;
import com.ccl.iot.batch.IOTBatchInterface;
import com.ccl.iot.bean.CodeviewBean;
import com.ccl.iot.device.IOTSubBLir;
import com.ccl.iot.dvr.utils.CommonUtils;
import com.ccl.iot.ir.DBUtils;
import com.ccl.iot.publics.ThreadPoolUtils;
import com.ccl.iot.publics.UIUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Set;

public class CustomBlirContrlView extends GridView {

    private IOTSubBLir mSubBLir;
    private CustomBlirAdapter mAdapter;
    private SubBlirControlView.OnDevOnlineChangeListener mOnlineChangeListener;
    private View mOfflineMask;
    private boolean mCheckable;

    private IOTBatchInterface.IOTBlirViewCheckInterface mLastCheckView;

    public CustomBlirContrlView(Context context) {
        this(context, null);
    }

    public CustomBlirContrlView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public CustomBlirContrlView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    private void init() {
        this.setColumnWidth(UIUtils.dp2px(3));
        this.setNumColumns(3);
        this.setSelector(new ColorDrawable(Color.TRANSPARENT));
        this.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                new SendIrTask(getContext(), mSubBLir, mOnlineChangeListener, mOfflineMask).execute(((CodeviewBean) mAdapter.getItem(position)).KeyType);
            }
        });

        this.setOnItemLongClickListener(new OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, final int position, long id) {
                final String items[] = {getResources().getString(R.string.Rename), getResources().getString(R.string.Delete), getResources().getString(R.string.blir_restudy)};
                AlertDialog.Builder builder = new AlertDialog.Builder(getContext(), AlertDialog.THEME_DEVICE_DEFAULT_LIGHT);
                builder.setItems(items, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        final CodeviewBean item = mAdapter.getItem(position);
                        if (item != null) {
                            if (which == 0) {
                                CommonUtils.getInputDialogDialog(getContext(), new CommonUtils.OnEnterInputListener() {
                                    @Override
                                    public void onEnterInput(final String text) {
                                        ThreadPoolUtils.getInstance().addTask(new Runnable() {
                                            @Override
                                            public void run() {
                                                DBUtils.updateCodeByID(item.DevID, item.SubDevID, item.CodeID, text, item.KeyType, item.aCode);
                                                item.KeyName = text;
                                                UIUtils.postTaskSafely(new Runnable() {
                                                    @Override
                                                    public void run() {
                                                        mAdapter.notifyDataSetChanged();
                                                    }
                                                });
                                            }
                                        });
                                    }

                                    @Override
                                    public void onCancel() {

                                    }
                                }, R.string.hint_input_name, -1);
                            } else if (which == 1) {
                                ThreadPoolUtils.getInstance().addTask(new Runnable() {
                                    @Override
                                    public void run() {
                                        DBUtils.removeCodeById(item.DevID, item.SubDevID, item.CodeID);
                                        HashMap<String, CodeviewBean> irCode = mSubBLir.getIRCode();
                                        if(irCode != null && irCode.size() > 0){
                                            irCode.remove(item.KeyType);
                                        }
                                        UIUtils.postTaskSafely(new Runnable() {
                                            @Override
                                            public void run() {
                                                mAdapter.notifyDataSetChanged();
                                            }
                                        });
                                    }
                                });
                            } else if (which == 2) {
                                new StudyIrTask(getContext(), mSubBLir, mOnlineChangeListener, mOfflineMask).execute(item.KeyType, item.KeyName);
                            }
                        }
                    }
                });

                builder.show();
                return true;
            }
        });

        mAdapter = new CustomBlirAdapter(getContext());
        this.setAdapter(mAdapter);
    }

    private String mLastCheckedTag = null;
    private IOTBatchInterface.OnBlirViewChecked mOnBlirViewChecked = new IOTBatchInterface.OnBlirViewChecked() {
        @Override
        public void onChected(boolean checked, String tag, IOTBatchInterface.IOTBlirViewCheckInterface view) {
            if (checked) {

                CodeviewBean batchCodes = mSubBLir.getBatchCodes();
                if (batchCodes != null) {
                    if (!tag.equals(batchCodes.KeyType)) {

                        mSubBLir.setBatchCodes(tag);
                        mLastCheckedTag = tag;
                        mAdapter.notifyDataSetChanged();
                    }
                } else {
                    mSubBLir.setBatchCodes(tag);
                    mLastCheckedTag = tag;
                    mAdapter.notifyDataSetChanged();
                }
            } else {
                CodeviewBean batchCodes = mSubBLir.getBatchCodes();
                if (batchCodes != null && tag.equals(mLastCheckedTag)) {
                    mSubBLir.setBatchCodes("");
                    mAdapter.notifyDataSetChanged();
                }
            }
        }
    };

    private IOTSubBLir.OnCheckedClearListener mCheckedClearListener = new IOTSubBLir.OnCheckedClearListener() {
        @Override
        public void onCheckedClear() {
            mAdapter.notifyDataSetChanged();
        }
    };

    public void setSubDev(IOTSubBLir subDev, SubBlirControlView.OnDevOnlineChangeListener l, View maskView, boolean checkable) {
        mCheckable = checkable;
        mOnlineChangeListener = l;
        mOfflineMask = maskView;
        mSubBLir = subDev;
        mSubBLir.setOnCheckedClearListener(mCheckedClearListener);
        mAdapter.notifyDataSetChanged();
    }

    class CustomBlirAdapter extends CustomAdapter<CodeviewBean> {

        private ImageView mLastView;

        private CommonUtils.OnEnterInputListener mKeyNameListener = new CommonUtils.OnEnterInputListener() {
            @Override
            public void onEnterInput(String text) {
                new StudyIrTask(getContext(), mSubBLir, mOnlineChangeListener, mOfflineMask).execute("Custom" + (getCount() - 1), text);
            }

            @Override
            public void onCancel() {

            }
        };

        public CustomBlirAdapter(Context context) {
            super(context);
        }

        @Override
        public List getDevList() {
            if (mSubBLir != null) {
                HashMap<String, CodeviewBean> irCodes = mSubBLir.getIRCode();
                if (irCodes != null && irCodes.size() > 0) {
                    ArrayList<CodeviewBean> codeBeans = new ArrayList<CodeviewBean>();
                    Set<String> keys = irCodes.keySet();
                    for (String key : keys) {
                        codeBeans.add(irCodes.get(key));
                    }
                    return codeBeans;
                }
            }
            return null;
        }

        @Override
        public View getLastView() {
            if (mLastView == null) {
                mLastView = new ImageView(getContext());
                mLastView.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, UIUtils.dp2px(48)));
                mLastView.setBackgroundResource(R.drawable.selector_custom_ir_btn_bg);
                mLastView.setImageResource(R.drawable.icon_add_blue);
                mLastView.setOnClickListener(new OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        CommonUtils.getInputDialogDialog(getContext(), mKeyNameListener, R.string.hint_input_name, -1);
                    }
                });
            }
            return mLastView;
        }

        @Override
        public View getNormalView(int position) {
            View view = View.inflate(getContext(), R.layout.view_custom_blir_item, null);
            view.setTag(view.findViewById(R.id.ml_keyname));
            return view;
        }

        @Override
        public void bindNormalView(View convertView, int position) {
            CheckableCustomIrView mlKeyName = (CheckableCustomIrView) convertView.getTag();
            CodeviewBean item = getItem(position);
            mlKeyName.setText(item.KeyName);
            mlKeyName.setTag(item.KeyType);
            mlKeyName.setCheckable(mCheckable);
            if (mCheckable) {
                mlKeyName.setOnBlirViewChected(mOnBlirViewChecked);
                CodeviewBean batchCodes = mSubBLir.getBatchCodes();
                if (batchCodes != null) {
                    mlKeyName.setChecked(item.KeyType.equals(batchCodes.KeyType));
                } else {
                    mlKeyName.setChecked(false);
                }
            } else {
                mlKeyName.setOnBlirViewChected(null);
            }
        }
    }

}
